﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Win32;
using OpenNETCF.WindowsCE;
using System.Runtime.InteropServices;
using System.Threading;


namespace PC_Asset_Geo_Tagging
{
    class PCTagger
    { 
        StreamWriter sw;
        static int count = 0;
        int time;
        const int DEFAULT_TIME = 20 ;//* 1000;
        //Timer cellInfoTimer;
        LargeIntervalTimer lit;

        public PCTagger()
        {
            Thread t = new Thread(new ThreadStart(initializeTimer));
            t.Start();
            //initializeTimer();
        }

        private void initializeTimer()
        {
            //TimerCallback timerDelegate = new TimerCallback(cellInfoOnTimedEvent);
            //cellInfoTimer = new Timer(timerDelegate, null, DEFAULT_TIME, DEFAULT_TIME);
            
            //以下代码用于将采集数据写入注册表
            //readRecord();
            lit = new LargeIntervalTimer();
            lit.FirstEventTime = DateTime.Now;
            lit.OneShot = false;
            lit.Interval = new TimeSpan(0, 0, DEFAULT_TIME);
            lit.Tick += new EventHandler(cellInfoOnTimedEvent);
            lit.Enabled = true;
            //*/
            recordLog("Program start!");
        }

        /************************************************************************/
        /* 用于将采集数据写入注册表                                                           */
        /************************************************************************/
        private void readRecord()
        {
            try
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader(@"\Temp\CellIDLog1.txt"))
                {
                    string line;
                    // Read and display lines from the file until the end of 
                    // the file is reached.
                    line = sr.ReadLine();
                    while (line != null)
                    {
                        if (!(line.Equals("")))
                        {
                            updateRegistryKey(line);
                        }
                        line = sr.ReadLine();
                    }
                }
            }
            catch (Exception e)
            {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
        }

        /************************************************************************/
        /* 程序用来记录日志的方法，便于调试以及测试                             */
        /************************************************************************/
        private void recordLog(string message)
        {
            sw = new StreamWriter(@"\Program Files\PC Asset Geo Tagging\CellIDLog.txt", true, Encoding.ASCII);
            sw.WriteLine(message + "\n" + DateTime.Now.ToString("h:mm:ss"));
            sw.WriteLine();
            sw.Flush();
            sw.Close();
        }

        /************************************************************************/
        /* CellInfo计时器每次到点触发的方法，即记录一次CellID信息               */
        /************************************************************************/
        private void cellInfoOnTimedEvent(object myObject, EventArgs e)
        {//一条CellID记录的格式：towerInfo(CellID-LocationAreaCode-MobileCountryCode-MobileNetworkCode)@time(year-month-day|hour:minute:second)
         //相邻两条记录用"&"分隔
            string towerInfo = RILHelper.GetCellTowerInfo();
            DateTime today = DateTime.Now;
            //初始化失败
            if (towerInfo.Equals("Failed to initialize RIL"))
                recordLog("Error:RIL initialize failed!");
            else
            {
                String cellInfo = towerInfo + "@" + today.Year + "-" + today.Month + "-" + today.Day + "|" + (today.Hour - 1) + ":" + today.Minute + ":" + today.Second;
                //textBox1.Text = cellInfo;
                updateRegistryKey(cellInfo);
            }
            updateCellInfoTime();
        }

        /************************************************************************/
        /* 每次记录完一次CellID信息便读取一次注册表配置信息以更新记录周期       */
        /************************************************************************/
        private void updateCellInfoTime()
        {
            RegistryKey rk = Registry.LocalMachine.CreateSubKey("PC Asset Geo Tagging\\CellInfo");
            string configInfo = rk.GetValue("ConfigInfo") + "";
            if (configInfo.Equals(""))
            {
                rk.SetValue("ConfigInfo", DEFAULT_TIME + "", RegistryValueKind.String);
                configInfo = DEFAULT_TIME + "";
            }
            try
            {
                time = Int32.Parse(configInfo);
                /*Random r = new Random();
                int temp = r.Next(15, 30);
                time = temp;
                //*/
            }
            catch (System.FormatException ex)
            {
                time = DEFAULT_TIME;
            }
            //cellInfoTimer.Change(time , time);
            lit.Interval = new TimeSpan(0, 0, time);
            lit.Enabled = true;
            recordLog("Update cellID record circle to: " + time + "s");
        }

        /************************************************************************/
        /* 将获取的CellID等信息更新到手机注册表中，如果注册表被写满，则将最老的数据覆盖 */
        /************************************************************************/
        private void updateRegistryKey(string cellInfo)
        {
            ++count;
            RegistryKey rk = Registry.LocalMachine.CreateSubKey("PC Asset Geo Tagging\\CellInfo");
            string originData = rk.GetValue("Record") + "";
            if (!originData.Equals(""))
                originData += "&";
            try
            {
                rk.SetValue("Record", originData + /*"[" + count + "]" + */cellInfo, RegistryValueKind.String);
            }
            catch (System.IO.IOException ex)//已经写满，需要删除一些旧记录
            {
                int index = originData.IndexOf('&') + 1;
                originData = originData.Substring(index);
                index = originData.IndexOf('&') + 1;
                originData = originData.Substring(index);
                rk.SetValue("Record", originData + /*"[" + count + "]" +*/ cellInfo, RegistryValueKind.String);
            }
            Console.WriteLine(rk.GetValue("Record") + "");
            recordLog("Record a new CellID!\n" + cellInfo);
        }
        /*
        [DllImport("coredll.dll")]
        protected extern static UInt32 SetSystemPowerState(String pwsSystemState, UInt32 StateFlags, UInt32 Options);

        protected static readonly UInt32 POWER_STATE_ON = 0x00010000;

        protected static readonly UInt32 POWER_FORCE = 0x00001000;
        //*/
    }
}
